package com.atguigu.ajax.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(urlPatterns = "/DrawServlet")
public class DrawServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 绘制图片，作为响应返回
        String imagePath = "/images/aaa.jpg";
        String realPath = getServletContext().getRealPath(imagePath);
        FileInputStream fileInputStream = new FileInputStream(realPath);
        response.setContentType("image/jpeg");
        byte[] buffer = new byte[1024];
        int len = -1;
        ServletOutputStream outputStream = response.getOutputStream();
        while ((len = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
    }
}
